/*-----------------------------------------------------------------------*/
/* Low level disk I/O module SKELETON for FatFs     (C)ChaN, 2019        */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be        */
/* attached to the FatFs via a glue function rather than modifying it.   */
/* This is an example of glue functions to attach various exsisting      */
/* storage control modules to the FatFs module with a defined API.       */
/*-----------------------------------------------------------------------*/

#include "ff.h"			/* Obtains integer types */
#include "diskio.h"		/* Declarations of disk functions */
#include "stm32f4_sdio_sd.h"

/* Definitions of physical drive number for each drive */
#define DEV_SD		0	/* Example: Map SD card to physical drive 0*/

#define SD_BLOCKSIZE     512 

static volatile DSTATUS currStat = STA_NOINIT;	/* Physical drive status */
extern SD_CardInfo SDCardInfo;

/*-----------------------------------------------------------------------*/
/* Get Drive Status                                                      */
/*-----------------------------------------------------------------------*/

DSTATUS disk_status (
	BYTE pdrv		/* Physical drive nmuber to identify the drive */
)
{
	DSTATUS stat = STA_NOINIT;
    if(pdrv == DEV_SD)
    {
        stat = currStat;
    }
	return stat;
}



/*-----------------------------------------------------------------------*/
/* Inidialize a Drive                                                    */
/*-----------------------------------------------------------------------*/

DSTATUS disk_initialize (
	BYTE pdrv				/* Physical drive nmuber to identify the drive */
)
{
	DSTATUS stat = STA_NOINIT;
    
    if(pdrv == DEV_SD)
    {
        if(SD_Init() == SD_OK)
        {
            stat &= ~STA_NOINIT;
        }else{
            stat = STA_NOINIT;
        }
        currStat = stat;
    }
	return stat;
}



/*-----------------------------------------------------------------------*/
/* Read Sector(s)                                                        */
/*-----------------------------------------------------------------------*/

DRESULT disk_read (
	BYTE pdrv,		/* Physical drive nmuber to identify the drive */
	BYTE *buff,		/* Data buffer to store read data */
	LBA_t sector,	/* Start sector in LBA */
	UINT count		/* Number of sectors to read */
)
{
	DRESULT res = RES_PARERR;
    SD_Error SD_state = SD_OK;
    
    if (!count) return RES_PARERR;					/* Check parameter */
	if (currStat & STA_NOINIT) return RES_NOTRDY;	/* Check if drive is ready */
    
	if(pdrv == DEV_SD)
    {
     	if(count ==  1){
			SD_state = SD_ReadBlock(buff, sector*SD_BLOCKSIZE, SD_BLOCKSIZE);
		}else{
			SD_state=SD_ReadMultiBlocks(buff,sector*SD_BLOCKSIZE,SD_BLOCKSIZE,count);
		}

		if(SD_state==SD_OK)
		{
			/* Check if the Transfer is finished */
			SD_state=SD_WaitReadOperation();
			
			/* Wait until end of DMA transfer */
			while(SD_GetStatus() != SD_TRANSFER_OK);
		}

		if(SD_state!=SD_OK)
			res = RES_PARERR;
		else
			res = RES_OK;  
   }

	return res;
}



/*-----------------------------------------------------------------------*/
/* Write Sector(s)                                                       */
/*-----------------------------------------------------------------------*/

#if FF_FS_READONLY == 0

DRESULT disk_write (
	BYTE pdrv,			/* Physical drive nmuber to identify the drive */
	const BYTE *buff,	/* Data to be written */
	LBA_t sector,		/* Start sector in LBA */
	UINT count			/* Number of sectors to write */
)
{
	DRESULT res = RES_PARERR;
	SD_Error SD_state = SD_OK;
    
    if (!count) return RES_PARERR;					/* Check parameter */
	if (currStat & STA_NOINIT) return RES_NOTRDY;	/* Check if drive is ready */
	if (currStat & STA_PROTECT) return RES_WRPRT;	/* Check write protect */


	if(pdrv == DEV_SD)
    {
       if(count ==  1){
			SD_state = SD_WriteBlock((uint8_t *)buff, sector*SD_BLOCKSIZE, SD_BLOCKSIZE);
		}else{
			SD_state=SD_WriteMultiBlocks((uint8_t *)buff,sector*SD_BLOCKSIZE,SD_BLOCKSIZE,count);
		}

		if(SD_state==SD_OK)
		{
			/* Check if the Transfer is finished */
			SD_state=SD_WaitWriteOperation();
			
			/* Wait until end of DMA transfer */
			while(SD_GetStatus() != SD_TRANSFER_OK);
		}

		if(SD_state!=SD_OK)
			res = RES_PARERR;
		else
			res = RES_OK;  
    }

	return res;
}

#endif


/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions                                               */
/*-----------------------------------------------------------------------*/

DRESULT disk_ioctl (
	BYTE pdrv,		/* Physical drive nmuber (0..) */
	BYTE cmd,		/* Control code */
	void *buff		/* Buffer to send/receive control data */
)
{
	DRESULT res = RES_PARERR;
	//int result;

	if(pdrv == DEV_SD)
    {
        switch (cmd) 
        {
            // Get R/W sector size (WORD) 
            case GET_SECTOR_SIZE :    
                *(WORD * )buff = SDCardInfo.CardBlockSize;
            break;
            // Get erase block size in unit of sector (DWORD)
            case GET_BLOCK_SIZE :      
                *(DWORD * )buff = SDCardInfo.CardBlockSize;
            break;

            case GET_SECTOR_COUNT:
                *(DWORD * )buff = SDCardInfo.CardCapacity/SDCardInfo.CardBlockSize;
                break;
            case CTRL_SYNC :
            break;
        }
        res = RES_OK;
    }
    
	return res;
}

